<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 订单列表
 * @package app\cms\admin
 */
class GoodsOrder extends Admin
{
    // 模型初始化
    protected static function init()
    {
        //TODO:初始化内容
    }

    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index()
    {
		//前置行为 
        cookie('__forward__', $_SERVER['REQUEST_URI']);
		//获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
		//dump($map);die;
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表.
		$store_id = 0;
		$store_map = [];
		
		//tab
        $list_tab = [
			'tab1' => ['title' => '待支付', 'url' => url('index', ['group' => 'tab1'])],
            'tab2' => ['title' => '已支付(待出库)', 'url' => url('index', ['group' => 'tab2'])],
            'tab3' => ['title' => '已支付(待确认)', 'url' => url('index', ['group' => 'tab3'])],
            'tab4' => ['title' => '已支付(已提货)', 'url' => url('index', ['group' => 'tab4'])],
            'tab5' => ['title' => '已取消', 'url' => url('index', ['group' => 'tab5'])],
            'tab6' => ['title' => '已过期', 'url' => url('index', ['group' => 'tab6'])],
        ];
		 // 数据列表
        $group = isset($data['group']) ? $data['group'] : 'tab2';
        switch ($group) {
            case 'tab1':
                $map[] = ['pay_status', '=', 0];
                break;
			case 'tab2':
                $map[] = ['pay_status', '=', 1];
                break;
			case 'tab3':
                $map[] = ['pay_status', '=', 5];
                break;
			case 'tab4':
                $map[] = ['pay_status', '=', 2];
                break;
			case 'tab5':
                $map[] = ['pay_status', '=', 3];
                break;
			case 'tab6':
                $map[] = ['pay_status', '=', 4];
                break;
        }
		
		if($sotre_user['store_uid'] > 0){
			$map[] = ['store_id', '=', $sotre_user['store_id']];
			$store_map['id'] = $sotre_user['store_id'];
			$store_id = $sotre_user['store_id'];
		}
        //数据列表
		$data_list = model('ErpGoodsOrder', 'model') -> withTrashed() -> where($map) -> order('id desc') -> paginate();
		
		foreach($data_list as $key => $value){
			$data_list[$key]['nick_name'] = model('user_center/Member', 'model\user') -> find($value['uid']) -> nick_name;
			$data_list[$key]['store'] 	  = model('ErpStore') -> find($value['store_id']) -> title;
		}
		
		$btn_details = [
			'title' => '详情',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('details', ['id' => '__id__']),
		];
		
		$btn_out = [
			'title' => '订单出库',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-primary',
			'href'  => url('details', ['id' => '__id__']),
		];

		$btn_xianjin = [
			'title' => '现金支付',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-primary',
			'href'  => url('details', ['id' => '__id__']),
		];
		
		//<!--JS 页面自动刷新 -->
		// echo ("<script type=\"text/javascript\">");
		// echo ("function fresh_page(){window.location.reload();}"); 
		// echo ("setTimeout('fresh_page()',3600);"); 
		// echo ("</script>");
	
$js = <<<EOF
		<script type="text/javascript">
			function fresh_page(){
				window.location.reload();
			}
			setTimeout('fresh_page()',120000);
		</script>
EOF;
	
		$store_list = model('ErpStore') -> where($store_map) -> column('id,title');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('订单列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_order') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '订单id'],
                ['nick_name', '下单人', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['ordercode', '订单号'],
                ['store', '门店'],
                ['pay_type', '支付方式', 'status', '', ['暂无:default' ,1=>'微信Wechat:success', 2=>'支付宝Alipay', 3=>'现金支付:warning', 4=>'余额支付:danger']],
				['pay_price', '金额'],
                ['pay_status', '订单状态', 'status', '', [0 => '待支付:warning', 1=>'已支付(待出库):success', 5 =>'已支付(待确认):success', 2=>'已完成(已提货)', 3 => '已取消:default', 4 => '已过期:danger']],
				['ps_type', '配送方式', [1 => '自提', 2=>'邮寄']],
				//['ck_type', '提货状态', [1 => '待提货', 2=>'已提货']],
                ['create_time', '下单时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([ 
				['select', 'pay_type', '支付方式', '', '',  [1 => '微信支付', 2 => '支付宝', 3 => '现金支付', 4=>'余额支付']],
                ['select', 'store_id', '下单门店', '', $store_id,  $store_list],
                ['text', 'ordercode', '订单号', 'like'],
				['daterange', 'create_time', '创建时间'],
            ])
            ->addRightButton('btn_details', $btn_details, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
            ->addRightButton('btn_out', $btn_out, ['area' => ['50%', '80%']])
            ->addRightButton('btn_xianjin', $btn_xianjin, ['area' => ['50%', '80%']])
            ->replaceRightButton(['pay_status' => ['eq', '1']], '', ['btn_details'])
            ->replaceRightButton(['pay_status' => ['eq', '0'], 'pay_type' => ['eq', 3]], '', ['btn_details'])
            ->replaceRightButton(['pay_status' => ['neq', '1']], '', ['btn_out'])
            ->replaceRightButton(['pay_status' => ['neq', '0']], '', ['btn_xianjin'])
            ->replaceRightButton(['pay_type' => ['neq', '3']], '', ['btn_xianjin'])
			->setTabNav($list_tab, $group)
			->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	//现金支付
	public function order_buy($id = ''){
		DB::startTrans();//启动事务
		$map = [];
		$map['id'] 		= $id;
		
		$data = [];
		$data['pay_status'] = 2; //订单出库
		
		$res = model('ErpGoodsOrder') -> update($data, $map);
		if(!$res){
			DB::rollback();
			$this->error('订单确认失败，请重试');
		}
		
		$store_id = model('ErpGoodsOrder') -> find($id) -> store_id;
		$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
		foreach ($warehouse_list['data'] as $key => $value) {
			if($value['type'] == 1){//分店仓库
				$store_warehouse_list[] = $value['wid'];
			}
		}
		$warehouse_id = $store_warehouse_list[0];
		
		$sku_list = model('ErpGoodsOrderSkulist') -> where('order_id', $id) -> column('id,sku_id,num');
		
		foreach($sku_list as $value){
			//变更库存
			$map = [];
			$map['sku_id'] 		 = $value['sku_id'];
			$map['warehouse_id'] = $warehouse_id;
			$stock_info  = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();
			$frozen_num  = $stock_info['frozen_num'] - $value['num'];//冻结数扣除
			$stock_num   = $stock_info['available_num'] + $frozen_num;//总库存减少
			
			
			$data = [];
			$data['stock_num']   = $stock_num;
			$data['frozen_num']  = $frozen_num;
			$rel = model('ErpGoodsWarehouseStockNum') -> save($data, $map);
			
			if(!$rel){
				DB::rollback();
				$this->error('订单确认失败，请重试');
			}
		}
		DB::commit();
		$this->success('订单确认成功，请提醒用户进行评价哦', cookie('__forward__'), '_parent_reload');
	}
	
	//订单出库
	public function order_out($id = ''){
		//取消订单
		$map = [];
		$map['id'] 		= $id;
		
		$data = [];
		$data['pay_status'] = 5; //订单出库
		
		$res = model('ErpGoodsOrder') -> update($data, $map);
		if(!$res){
			$this->error('出库失败，请重试！');
		}
		$this->success('订单已出库，请提醒用户刷新订单页面！', cookie('__forward__'), '_parent_reload');
	}

	//订单详情
	public function details($id = []){
		$info = model('ErpGoodsOrder') -> withTrashed() -> find($id);

		$info['nick_name'] = model('user_center/Member', 'model\user') -> find($info['uid']) -> nick_name;
		$info['store'] 	  = model('ErpStore') -> find($info['store_id']) -> title;
		
		$table_data = [
			['sku_id', '购买商品', '价格', '数量'],
		];
		$order_sku = model('ErpGoodsOrderSkulist') -> where('order_id', $id) -> column('sku_id,num,price');
		foreach($order_sku as $value){
			$goods_info = model('ErpGoodsSku') -> find($value['sku_id']);
			if($goods_info['goods_specifications'] != ''){
				$goods_name = $goods_info['goods_name'] . ' - ' . $goods_info['goods_specifications'];
			}else{
				$goods_name = $goods_info['goods_name'];
			}
			
			$table_data[] = [$value['sku_id'], $goods_name, $value['price'], $value['num']];
		}

        $hideBtn    = ['submit', 'back'];
        $titleBtn   = ['submit' => '确认出库'];
        $setUrl     = url('/erp/goods_order/order_out/id/' . $id); //订单出库
		switch ($info['pay_status']) {
			case 0;
			    if($info['pay_type'] == 3){
                    $hideBtn = ['back'];
                    $titleBtn   = ['submit' => '确认支付'];
                    $setUrl = url('/erp/goods_order/order_buy/id/' . $id);//确认支付
                }
				$info['pay_status'] = '待支付';
				break;
			case 1;
                $titleBtn = ['submit' => '确认出库'];
                $hideBtn  = ['back'];
				$info['pay_status'] = '已支付(待出库)';
				break;
			case 2;
				$info['pay_status'] = '已完成';
				break;
			case 3;
				$info['pay_status'] = '已取消';
				break;
			case 4;
				$info['pay_status'] = '已过期';
				break;
			case 5;
                $info['pay_status'] = '已支付(已出库)';
                break;
		}

        $pay_type = ['暂无', '微信', '支付宝', '现金', '余额'];

        $info['pay_type'] = $pay_type[$info['pay_type']];
        $info['ps_type'] = $info['ps_type'] == 1 ? '自提' : '邮寄';
        $info['pay_expiration_time'] = date('Y-m-d H:i:s', $info['pay_expiration_time']);

		//批量审核最多允许20个
		return ZBuilder::make('form')
            ->setPageTitle('订单详情') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
				['text', 'id', '订单id', '', '', '', 'readonly="readonlys"'],
				['text', 'nick_name', '下单人', '', '', '', 'readonly="readonlys"'],
				['text', 'ordercode', '订单号', '', '', '', 'readonly="readonlys"'],
				['text', 'store', '门店', '', '', '', 'readonly="readonlys"'],
				['text', 'pay_type', '支付方式', '', '', '', 'readonly="readonlys"'],
				['text', 'pay_price', '支付金额', '', '', '', 'readonly="readonlys"'],
				['text', 'pay_status', '订单状态', '', '', '', 'readonly="readonlys"'],
				['text', 'ps_type', '配送方式', '', '', '', 'readonly="readonlys"'],
				['text', 'pay_expiration_time', '订单到期时间', '', '', '', 'readonly="readonlys"'],
			])
			->addFormItems([ // 批量添加表单项
				['complexTable', 'list_user', '采购单sku', $table_data]
			])
            ->setBtnTitle($titleBtn)
            ->setUrl($setUrl)
			->hideBtn($hideBtn)
			->setFormData($info) // 设置表单数据
            ->fetch();
	}
}